package com.demo.filter;

import com.alibaba.fastjson2.JSON;
import com.demo.common.BaseContext;
import com.demo.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "/loginCheckFilter", urlPatterns = "/*")
//定义过滤器，负责拦截未登录直接访问后台
public class LoginCheckFilter implements Filter {
    //路径匹配器，可以适配通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        //获取到当前路径
        String requestURI = request.getRequestURI();

//        log.info("拦截到的路径为：{}",requestURI);
        //定义白名单
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };


        //判断当前路径是否包含白名单，如果包含，直接放行
        boolean checkout = checkout(urls, requestURI);

        if (checkout) {
//            log.info("本次请求不需要处理 {}" ,requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //获取后端登录session中的数据
        //判断session中的数据是否为空，如果不为空就放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("本次登录的id为：{}",request.getSession().getAttribute("employee"));

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);


            long id = Thread.currentThread().getId();
            log.info("当前线程id为 {}" ,id);
            filterChain.doFilter(request, response);
            return;
        }


        //获取APP登录session中的数据
        //判断session中的数据是否为空，如果不为空就放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("本次登录的id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);


            long id = Thread.currentThread().getId();
            log.info("当前线程id为 {}" ,id);
            filterChain.doFilter(request, response);
            return;
        }



        //如果未登录则返回未登录结果
//        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    /**
     * 判断路径是否包含白名单
     *
     * @param requestURI
     * @param urls
     * @return
     */
    public boolean checkout(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
